如果需要使用者傳遞檔案,要先建個資料夾在專案根目錄使用 POST 上傳,檔案就會傳到剛剛建好的資料夾裡
輸入參數選 Body
-> form-data
, 檔案先放在 C:/Users/<user name>/Postman/files
裡面;KEY
格式選 File
, VALUE
選擇檔案後按 Send
app.py
import os
from flask import Flask, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config["DEBUG"] = True
app.config["ALLOW_EXTENSIONS"] = ['jpg']
def is_allow_extensions(filename): # 判斷副檔名是否允許上傳
return ('.' in filename) and (filename.split('.')[-1].lower() in app.config['ALLOW_EXTENSIONS'])
@app.route("/", methods=["POST"])
def file_upload():
f = request.files["files"]
filename = secure_filename(f.filename)
if is_allow_extensions(filename):
f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'success'
else:
return 'error'
if __name__ == "__main__":
app.run()
執行結果